package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.util.Map;

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);

        try {
            // 获取数据源实例
            DataSource dataSource = ctx.getBean(DataSource.class);
            System.out.println("数据源实现类: " + dataSource.getClass().getName());

            // 通过反射获取私有字段
            Class<?> clazz = dataSource.getClass();
            Field dataSourceField = clazz.getDeclaredField("dataSourceMap");
            dataSourceField.setAccessible(true);

            // 获取数据源Map
            Map<?, ?> dataSources = (Map<?, ?>) dataSourceField.get(dataSource);
            System.out.println("已加载数据源: " + dataSources.keySet());

            // 获取主数据源
            Field primaryField = clazz.getDeclaredField("primary");
            primaryField.setAccessible(true);
            System.out.println("主数据源: " + primaryField.get(dataSource));

        } catch (Exception e) {
            System.err.println("验证失败，请检查以下配置：");
            System.err.println("1. 确认使用 dynamic-datasource 2.5.6 版本");
            System.err.println("2. 检查 application.yml 中是否配置了多个数据源");
            System.err.println("3. 启动日志中是否有数据源初始化报错");
            e.printStackTrace();
        }
    }
}